<template>
  <div class="station-management">
    <div class="header">
      <h2>车站管理</h2>
      <el-button type="primary" @click="showCreateDialog">
        <el-icon><Plus /></el-icon>
        添加车站
      </el-button>
    </div>

    <el-table :data="stations" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="stationCode" label="车站代码" width="120" />
      <el-table-column prop="stationName" label="车站名称" width="180" />
      <el-table-column prop="city" label="城市" width="120" />
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button size="small" @click="editStation(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteStation(row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑车站对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑车站' : '添加车站'"
      width="500px"
    >
      <el-form :model="stationForm" :rules="rules" ref="stationFormRef" label-width="100px">
        <el-form-item label="车站代码" prop="stationCode">
          <el-input v-model="stationForm.stationCode" placeholder="请输入车站代码" />
        </el-form-item>
        <el-form-item label="车站名称" prop="stationName">
          <el-input v-model="stationForm.stationName" placeholder="请输入车站名称" />
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-input v-model="stationForm.city" placeholder="请输入城市" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveStation">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { stationApi } from '@/api/train'
import type { Station } from '@/types/train'

const stations = ref<Station[]>([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const stationFormRef = ref()

const stationForm = reactive({
  id: null as number | null,
  stationCode: '',
  stationName: '',
  city: ''
})

const rules = {
  stationCode: [
    { required: true, message: '请输入车站代码', trigger: 'blur' },
    { min: 2, max: 10, message: '车站代码长度在2到10个字符', trigger: 'blur' }
  ],
  stationName: [
    { required: true, message: '请输入车站名称', trigger: 'blur' },
    { min: 2, max: 50, message: '车站名称长度在2到50个字符', trigger: 'blur' }
  ],
  city: [
    { required: true, message: '请输入城市', trigger: 'blur' },
    { min: 2, max: 50, message: '城市长度在2到50个字符', trigger: 'blur' }
  ]
}

// 获取车站列表
const fetchStations = async () => {
  try {
    const response = await stationApi.getAllStations()
    if (response.success) {
      stations.value = response.data
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('获取车站列表失败:', error)
    ElMessage.error('获取车站列表失败')
  }
}

// 显示创建对话框
const showCreateDialog = () => {
  resetForm()
  isEdit.value = false
  dialogVisible.value = true
}

// 编辑车站
const editStation = (station: Station) => {
  Object.assign(stationForm, station)
  isEdit.value = true
  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  Object.assign(stationForm, {
    id: null,
    stationCode: '',
    stationName: '',
    city: ''
  })
  stationFormRef.value?.clearValidate()
}

// 保存车站
const saveStation = async () => {
  try {
    const valid = await stationFormRef.value.validate()
    if (!valid) return
    
    let response
    if (isEdit.value && stationForm.id !== null) {
      response = await stationApi.updateStation(stationForm.id, stationForm)
    } else {
      response = await stationApi.createStation(stationForm)
    }
    
    if (response.success) {
      ElMessage.success(response.message)
      dialogVisible.value = false
      fetchStations()
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error(isEdit.value ? '更新车站失败' : '创建车站失败', error)
    ElMessage.error(isEdit.value ? '更新车站失败' : '创建车站失败')
  }
}

// 删除车站
const deleteStation = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个车站吗？', '确认删除', {
      type: 'warning'
    })
    
    const response = await stationApi.deleteStation(id)
    if (response.success) {
      ElMessage.success(response.message)
      fetchStations()
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除车站失败:', error)
      ElMessage.error('删除车站失败')
    }
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString()
}

onMounted(() => {
  fetchStations()
})
</script>

<style scoped>
.station-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}
</style>